# -*- coding: utf-8 -*-
# This code written by ChanGOGOGO
"""
话单明细
"""
import pymysql
import time
from util import (
    query_es,
    date_slice,
    ms2min,
    setup_logging,
    data2beautify,
    write_excel,
    logging,
    per_excel_data_num,
    db_ip,
    db_port,
    db_username,
    db_password,
    excel_save_dir,
)


class ExportBillsDetail:
    def __init__(self, ui_data):
        self.data_date = ui_data.get("data_date")
        self.task_ids = ui_data.get("target_datas")
        self.start_time = ui_data.get("start_time")
        self.end_time = ui_data.get("end_time")
        self.business = ui_data.get("business")
        self.data_type = ui_data.get("data_type")
        self.call_type = ui_data.get("call_type")
        company_id = ui_data.get("company_id")
        self.db_name = f"yicall_{company_id}"
        self.table_index = ui_data.get("business_id")
        if self.call_type == "呼出":
            self.es_index = f"{self.db_name}_{self.table_index}_callout_session_ach_{self.data_date}"
        else:
            self.es_index = f"{self.db_name}_{self.table_index}_callout_session_in_ach_{self.data_date}"
        self.conn = pymysql.connect(
            host=db_ip,
            port=db_port,
            user=db_username,
            passwd=db_password,
            charset="utf8",
        )
        self.cursor = self.conn.cursor()
        self.task_info = self.query_task_info()
        self.close_db()

    def query_task_info(self):
        """查询任务信息"""
        if self.call_type == "呼出":
            sql = f"""select task_id,task_name from {self.db_name}.b_{self.table_index}_callout_task;"""
        else:
            sql = f"""select task_id,task_name from {self.db_name}.b_{self.table_index}_callout_task_in;"""
        logging.info(f"查询{self.business}任务信息SQL:\n{sql}")
        self.cursor.execute(sql)
        result = self.cursor.fetchall()
        task_info = dict()
        if result:
            task_info = {task_id: task_name for task_id, task_name in result}
        logging.info(f"获取到{self.business}下的任务信息：\n{data2beautify(task_info)}")
        return task_info

    def close_db(self):
        self.cursor.close()
        self.conn.close()

    def query_es_data(self, day_start_time, day_end_time):
        """"""
        task_id_num = len(self.task_ids)
        fields = [
            "taskId",
            "calloutDialNumber",
            "dialNumber",
            "dialogDuration",
            "calloutDialTime",
        ]
        if task_id_num == 0:
            body = {
                "query": {
                    "bool": {
                        "must": [
                            {"term": {"calloutConnectStatus": 100}},
                            {
                                "range": {
                                    "calloutFinishTime": {
                                        "gte": day_start_time,
                                        "lte": day_end_time,
                                    }
                                }
                            },
                        ]
                    }
                },
                "sort": {"calloutDialTime": {"order": "asc"}},
            }
        else:
            body = {
                "query": {
                    "bool": {
                        "must": [
                            {"term": {"calloutConnectStatus": 100}},
                            {"terms": {"taskId": self.task_ids}},
                            {
                                "range": {
                                    "calloutFinishTime": {
                                        "gte": day_start_time,
                                        "lte": day_end_time,
                                    }
                                }
                            },
                        ]
                    }
                },
                "sort": {"calloutDialTime": {"order": "asc"}},
            }
        day_es_data = query_es(self.es_index, body, fields)
        return day_es_data

    def export(self):
        """导出通话时长数据"""
        handled_data = list()
        # 以“天”为单位查询es数据，避免scroll超时
        date_slice_result = date_slice(self.start_time, self.end_time)
        for everyday in date_slice_result:
            day_start_time = everyday[0]
            day_end_time = everyday[1]
            day_es_data = self.query_es_data(day_start_time, day_end_time)
            try:
                for data in day_es_data:
                    task_id = data.get("taskId")
                    task_name = self.task_info.get(int(task_id))
                    callout_dial_number = data.get("calloutDialNumber")
                    callout_dial_time = data.get("calloutDialTime")
                    dial_number = data.get("dialNumber")
                    dialog_duration_ms = int(data.get("dialogDuration"))
                    dialog_duration_min = ms2min(dialog_duration_ms)
                    handled_data.append(
                        [
                            task_id,
                            task_name,
                            callout_dial_number,
                            dial_number,
                            callout_dial_time,
                            dialog_duration_ms,
                            dialog_duration_min,
                        ]
                    )
            except Exception as reason:
                logging.error(reason)
        total_data = len(handled_data)
        logging.info(
            f"{self.business}从{self.start_time}至{self.end_time}共查询到{total_data}条话单数据。"
        )
        if total_data < 1:
            msg = (
                f"⚠️ <font color='red'>**{self.business}**</font>的<font color='green'>{self.data_type}</font>导出失败。"
                f"原因：\n<font color='blue'>在{self.start_time}至{self.end_time}没有查询到{self.call_type}数据！</font>"
            )
            logging.warning(msg)
            return {"code": 1, "excel_names": [], "msg": msg}
        else:
            if self.call_type == "呼出":
                sheet_title = [
                    "任务ID",
                    "任务名",
                    "主叫号码",
                    "被叫号码",
                    "通话时间",
                    "通话时长(毫秒)",
                    "通话时长(分钟)",
                ]
            else:
                sheet_title = [
                    "任务ID",
                    "任务名",
                    "被叫号码",
                    "主叫号码",
                    "通话时间",
                    "通话时长(毫秒)",
                    "通话时长(分钟)",
                ]
            excel_names = list()
            excel_batches = (
                total_data + per_excel_data_num - 1
            ) // per_excel_data_num  # 计算需要多少个excel存储数据
            data_index = 0
            write_excel_start_time = time.time()
            for i in range(excel_batches):
                single_excel_data = handled_data[
                    data_index : data_index + per_excel_data_num
                ]
                data_index += per_excel_data_num
                sheet_infos = [[self.data_type, sheet_title, single_excel_data]]
                if excel_batches > 1:
                    file_name = f"{self.business}_({self.call_type}){self.data_type}_第{i + 1}批"
                else:
                    file_name = f"{self.business}_({self.call_type}){self.data_type}"
                excel_name = write_excel(sheet_infos, excel_save_dir, file_name, True)
                excel_names.append(excel_name)
            write_excel_end_time = time.time()
            write_excel_take_time = write_excel_end_time - write_excel_start_time
            logging.info(
                f"将{self.business}的{self.data_type}写入excel共计耗时{write_excel_take_time:.2f}秒。"
            )
            return {"code": 0, "excel_names": excel_names, "msg": None}


if __name__ == "__main__":
    ...
